package org.mebusw.struts.davincicode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Random;

/**
 * @author j1shen
 * @see DavinciCard
 * @see CardHand
 */
public class CardPool extends ArrayList<DavinciCard> implements Serializable {

	int cardIndex;

	public CardPool() {
		this.Init();
	}

	public void Init() {
		DavinciCard card = null;

		cardIndex = 0;
		this.clear();
		for (int i = 0; i <= 11; i++) {
			// black card
			card = new DavinciCard(DavinciCard.BLACK, i, DavinciCard.NONJOKER,
					-1);
			this.add(card);
			// white card
			card = new DavinciCard(DavinciCard.WHITE, i, DavinciCard.NONJOKER,
					-1);
			this.add(card);
		}
		// the two jokers
		card = new DavinciCard(DavinciCard.BLACK, DavinciCard.JOKER99,
				DavinciCard.JOKER, -1);
		this.add(card);
		card = new DavinciCard(DavinciCard.BLACK, DavinciCard.JOKER99,
				DavinciCard.JOKER, -1);
		this.add(card);

		for (int i = 0; i < this.size(); i++) {
			this.get(i).setUncover(DavinciCard.STANDING);
		}
		Collections.shuffle(this);
		
		System.out.println("cardpool.init(): " + this.size());
	}

	/**
	 * player takes one card randomly from the pool on the table and a card Id
	 * will be given
	 * 
	 * @return DavinciCard
	 * @see CardHand
	 */
	public DavinciCard randTake() {

		DavinciCard card = null;
		Date t = new Date(System.currentTimeMillis());
		Random rand = new Random(t.getTime());

		if (this.size() <= 0)
			return null;
		try {
			int index = rand.nextInt(this.size());
			card = this.get(index);
			this.remove(index);
			card.setCardId(cardIndex);
			cardIndex++;
		} catch (Exception e) {
			System.out.println("CardPool.randTake(): " + e);
		}
		System.out.printf("randTake: Value:%d IsBlack:%s ID:%d\n", card
				.getValue(), card.isBlack(), card.getCardId());
		return card;
		
		
	}
}
